<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 搜索区域 -->
    <div class="mx-auto max-w-8xl px-4 py-4 sm:px-6 lg:px-8">
      <div class="rounded-lg bg-white p-4 shadow">
        <div class="flex flex-wrap items-end gap-4">
          <div class="flex-1">
            <label class="mb-1 block text-sm font-medium text-gray-700">服务名称</label>
            <el-input
                v-model="searchParams.name"
                placeholder="请输入服务名称"
                @change="getPage"
                clearable
                class="w-full"
            />
          </div>
          <div class="flex-1">
            <label class="mb-1 block text-sm font-medium text-gray-700">服务分类</label>
            <el-select
              v-model="searchParams.categoryId"
              placeholder="请选择服务分类"
              @change="getPage"
              clearable
              class="w-full"
            >
              <el-option v-for="item in categories"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"/>
            </el-select>
          </div>
          <div class="flex-1">
            <label class="mb-1 block text-sm font-medium text-gray-700">服务状态</label>
            <el-select
                v-model="searchParams.status"
                placeholder="请选择服务状态"
                @change="getPage"
                clearable
                class="w-full"
            >
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="2" />
            </el-select>
          </div>
          <div>
            <el-button
                type="primary"
                class="!rounded-button whitespace-nowrap"
                @click="showAddDialog"
            >
              新建
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="mx-auto max-w-8xl px-4 py-4 sm:px-6 lg:px-8">
      <div class="overflow-hidden rounded-lg bg-white shadow">
        <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
            v-loading="loading"
            @sort-change="handleSortChange"
        >
          <el-table-column prop="id" label="序号" width="80" align="center" sortable="custom"/>
          <el-table-column label="服务图片" width="120" align="center">
            <template #default="{row}">
              <el-image
                  :src="`${SERVER_ADDR}/upload/${row.pic}`"
                  fit="cover"
                  class="w-16 h-16 rounded"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="服务名称" sortable="custom" width="120" />
          <el-table-column label="服务分类" width="150">
            <template #default="{ row }">
              {{ getCategoryName(row.categoryId) }}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="服务时长(h)" width="180" align="center" sortable="custom">
            <template #default="{ row }">
              {{ row.time }}h
            </template>
          </el-table-column>
          <el-table-column prop="frequency" label="建议频率" width="150" />
          <el-table-column prop="price" label="每小时价格" width="150"  sortable="custom" />
          <el-table-column label="服务状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column  label="服务简介" width="180">
            <template #default="{ row }">
              {{ row.description }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" align="center" fixed="right">
            <template #default="{ row }">
              <el-button
                  size="small"
                  class="!rounded-button whitespace-nowrap"
                  @click="showDetailDialog(row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button
                  size="small"
                  type="primary"
                  class="!rounded-button whitespace-nowrap"
                  @click="showEditDialog(row.id)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-dropdown trigger="click">
                <el-button
                    size="small"
                    type="info"
                    class="!rounded-button whitespace-nowrap"
                >
                  <el-icon><More /></el-icon>
                  更多
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="showEditDetailDialog(row)">
                      <el-icon><Document /></el-icon>
                      编辑详情
                    </el-dropdown-item>
                    <el-dropdown-item @click="showEditSpecDialog(row)">
                      <el-icon><Notebook /></el-icon>
                      编辑规范书
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(row)" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="flex items-center justify-end bg-white px-4 py-3">
          <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[7, 14, 21, 18]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务时长(h)" prop="time">
        <el-input-number
            v-model="formData.time"
            :min="0.5"
            :step="0.5"
            :precision="1"
            controls-position="right"
        />
      </el-form-item>
        <el-form-item label="服务分类" prop="categoryId">
          <el-select
              v-model="formData.categoryId"
              placeholder="请选择服务分类"
              class="w-full"
          >
            <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="建议频率" prop="frequency">
          <el-input v-model="formData.frequency" placeholder="例如: 1天/3次" />
        </el-form-item>
        <el-form-item label="每小时价格">
          <el-input v-model="formData.price" placeholder="服务的每小时价格" />
        </el-form-item>
        <el-form-item label="服务图片" prop="pic">
          <el-upload
              class="avatar-uploader"
              :action="`${SERVER_ADDR}/admin/file/upload`"
              name="pic"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="服务简介"
        >
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入服务简介"
          />
        </el-form-item>
        <el-form-item label="服务状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="服务详情"
        width="60%"
        :close-on-click-modal="false"
    >
      <div class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div>
            <h3 class="text-sm font-medium text-gray-500">服务名称</h3>
            <p class="mt-1 text-sm text-gray-900">{{ currentItem.name }}</p>
          </div>
          <div>
            <h3 class="text-sm font-medium text-gray-500">服务分类</h3>
            <p class="mt-1 text-sm text-gray-900">
              {{ getCategoryName(currentItem.categoryId) }}
            </p>
          </div>
          <div>
            <h3 class="text-sm font-medium text-gray-500">服务时长</h3>
            <p class="mt-1 text-sm text-gray-900">{{ currentItem.time }}h</p>
          </div>
          <div>
            <h3 class="text-sm font-medium text-gray-500">服务频率</h3>
            <p class="mt-1 text-sm text-gray-900">{{ currentItem.frequency }}</p>
          </div>
          <div>
            <h3 class="text-sm font-medium text-gray-500">服务状态</h3>
            <p class="mt-1 text-sm text-gray-900">
              <el-tag :type="currentItem.status === 1 ? 'success' : 'danger'">
                {{ currentItem.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </p>
          </div>
        </div>
        <div>
          <h3 class="text-sm font-medium text-gray-500">服务图片</h3>
          <div class="mt-1">
            <el-image
                :src="`${SERVER_ADDR}/upload/${currentItem.pic}`"
                fit="cover"
                class="w-40 h-40 rounded"
                :preview-src-list="[currentItem.pic]"
            >
              <template #error>
                <div class="w-40 h-40 flex items-center justify-center bg-gray-100 rounded">
                  <el-icon class="text-gray-400"><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </div>
        <div>
          <h3 class="text-sm font-medium text-gray-500">服务简介</h3>
          <p class="mt-1 text-sm text-gray-900">{{ currentItem.description }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 编辑详情弹窗 -->
    <el-dialog
        v-model="editDetailDialogVisible"
        width="70%"
        title="编辑详情"
        :close-on-click-modal="false"
    >
      <template #footer>
        <div  v-if="editDetailDialogVisible" style="border: 1px solid #ccc; margin-bottom: 5px;">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
          />
          <el-form-item label="内容">
            <QuillEditor v-model="formData.detail" />
          </el-form-item>
        </div>
        <el-button @click="editDetailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editDetail">
          确定
        </el-button>
      </template>
    </el-dialog>
    <!-- 编辑规范书弹窗 -->
    <el-dialog
        v-model="editSpecDialogVisible"
        title="编辑服务规范书"
        width="70%"
        :close-on-click-modal="false"
    >
      <template #footer>
        <div  v-if="editSpecDialogVisible" style="border: 1px solid #ccc; margin-bottom: 5px;">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
          />
          <el-form-item label="内容">
            <QuillEditor v-model="formData.specification" />
          </el-form-item>
        </div>
        <el-button @click="editSpecDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editDetail">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="js" setup>
import {ref, onMounted, nextTick, computed, shallowRef} from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import {
  Plus,
  Search,
  View,
  Edit,
  Delete,
  Document,
  Notebook,
  More,
  Picture,
} from '@element-plus/icons-vue';
import serviceApi from "@/api/admin/serviceApi.js";
import categoryApi from "@/api/admin/categoryApi.js";
import {useTokenStore} from "@/stores/token.js";
import {ElMessage, ElMessageBox} from "element-plus";
import QuillEditor from "@/components/common/QuillEditor.vue";
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const tokenStore = useTokenStore();
//上传图片
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
})
// 图片路径
const imageUrl = ref("");
// 服务分类
const categories = ref([]);
// 搜索参数
const searchParams = ref({
  name: null,
  categoryId: null,
  status: null,
});
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 7,
  total: 0,
});
// 排序参数
const sortParams = ref({
  prop: 'id',
  order: 'asc',
});
// 表格数据
const tableData = ref([]);
const loading = ref(false);
// 表单相关
const formRef = ref();
const dialogVisible = ref(false);
const dialogTitle = ref('新增护理服务');
const formData = ref({
  id: null,
  name: '',
  time: 0.5,
  categoryId: null,
  pic: '',
  description: '',
  detail: '',
  specification: '',
  frequency: '',
  status: 1,
});
const formRules = ref({
  name: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
  categoryId: [
    { required: true, message: '请选择服务分类', trigger: 'change' },
  ],
  time: [{ required: true, message: '请输入服务时长', trigger: 'blur' }],
  frequency: [{ required: true, message: '请输入服务频率', trigger: 'blur' }],
  description: [
    { required: true, message: '请输入服务简介', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择服务状态', trigger: 'change' }],
});
// 详情相关
const detailDialogVisible = ref(false);
const editDetailDialogVisible = ref(false);
const editSpecDialogVisible = ref(false);
const filterProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: false,
  clearable: true
};
const currentItem = ref({
  id: null,
  name: '',
  time: 0,
  categoryId: null,
  description: '',
  frequency: '',
  status: 1,
  pic: '',
});
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 设置wangEditor的内容
const mode = ref('default');
//工具栏的设置
const toolbarConfig = {}
// 获取所有的分类
const getCategory = () => {
  let category = {
    parentId: 0,
    categoryType: 1,
  };
  categoryApi.selectByPage(null, null, category)
      .then(resp => {
        if (resp.data && resp.data.length > 0) {
          categories.value = resp.data;
        } else {
          console.error('分类数据为空或未正确返回');
        }
      })
      .catch(error => {
        console.error('获取分类数据失败:', error);
      });
};
// 获取分类名称
const getCategoryName = (id) => {
  const category = categories.value.find((item) => item.id === id);
  return category ? category.name : '';
};
// 获取表格数据
const getPage = () => {
  serviceApi.selectByPage(pagination.value.currentPage,
      pagination.value.pageSize,
      sortParams.value.prop,
      sortParams.value.order,
      searchParams.value)
      .then((resp) => {
        if (resp.code == 10000) {
          tableData.value = resp.data.data;
          pagination.value.total = resp.data.total;
        }
      })
};
// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  getPage();
};
// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  getPage();
};
// 排序改变
const handleSortChange = ({ prop, order }) => {
  sortParams.value.prop = prop;
  if (order === 'ascending') {
    sortParams.value.order = 'asc';
  } else if (order === 'descending') {
    sortParams.value.order = 'desc';
  }
  getPage();
};
// 显示新增弹窗
const showAddDialog = () => {
  dialogTitle.value = '新增护理服务';
  Object.assign(formData, {
    id: null,
    name: '',
    categoryId: null,
    time: 0.5,
    frequency: '',
    description: '',
    status: 1,
  });
  imageUrl.value = '';
  dialogVisible.value = true;
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};
// 显示编辑弹窗
const showEditDialog = (id) => {
  dialogTitle.value = '编辑护理服务';
  serviceApi.selectById(id)
      .then((resp) => {
        if (resp.code == 10000){
          formData.value = resp.data;
          imageUrl.value = `${SERVER_ADDR.value}/upload/${resp.data.pic}`;
          dialogVisible.value = true;
          nextTick(() => {
            formRef.value?.clearValidate();
          });
        }
      });


};
// 显示详情弹窗
const showDetailDialog = (row) => {
  currentItem.value = { ...row };
  detailDialogVisible.value = true;
};
// 显示编辑详情弹窗
const showEditDetailDialog = (row) => {
  // 重置表单
  formData.value = {
    id: null,
    name: '',
    time: 0.5,
    categoryId: null,
    description: '',
    detail: '',
    specification: '',
    frequency: '',
    status: 1,
  };
  formData.value.id = row.id;
  formData.value.detail = row.detail;
  editDetailDialogVisible.value = true;
};
// 显示编辑规范书弹窗
const showEditSpecDialog = (row) => {
  // 重置表单
  formData.value = {
    id: null,
    name: '',
    time: 0.5,
    categoryId: null,
    description: '',
    detail: '',
    specification: '',
    frequency: '',
    status: 1,
  };
  formData.value.id = row.id;
  formData.value.specification = row.specification;
  editSpecDialogVisible.value = true;
};
// 提交表单
const handleSubmit = () => {
// 判断是否是新增还是修改
  if (dialogTitle.value === '新增护理服务') {
    serviceApi.insert(formData.value)
        .then(resp => {
          if (resp.code === 10000){
            ElMessage.success(resp.msg)
            dialogVisible.value = false;
            getPage();
            // 重置form里面的数据
            formData.value = {
              id: null,
              name: '',
              time: 0.5,
              categoryId: null,
              description: '',
              frequency: '',
              status: 1,
            }
          }else {
            ElMessage.error(resp.msg)
          }
        })
  }else if (dialogTitle.value === '编辑护理服务') {
    serviceApi.update(formData.value)
        .then(resp => {
          if (resp.code === 10000){
            ElMessage.success(resp.msg)
            dialogVisible.value = false;
            getPage();
            // 重置form里面的数据
            formData.value = {
              id: null,
              name: '',
              time: 0.5,
              categoryId: null,
              description: '',
              frequency: '',
              status: 1,
            }
          }else {
            ElMessage.error(resp.msg)
          }
        })
  }
};
// 修改详情和护理规格书的处理
const editDetail = () => {
  let service = {
    id: formData.value.id,
    detail: formData.value.detail,
    specification: formData.value.specification,
  };
  serviceApi.update(service)
      .then(resp => {
        if (resp.code === 10000){
          ElMessage.success(resp.msg)
          editDetailDialogVisible.value = false;
          editSpecDialogVisible.value = false;
          getPage();
        }else {
          ElMessage.error(resp.msg)
        }
      })
};
// 保存详情
const saveDetail = () => {

};
// 保存规范书
const saveSpec = () => {

};
// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该护理服务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
      })
      .catch(() => {});
};
// 图片上传处理
const handleImageSuccess = (response, file) => {
  if (response.code === 10000) {
    ElMessage.success('上传成功');
    imageUrl.value = `${SERVER_ADDR.value}/upload/${response.data}`;
    formData.value.pic = response.data;
  }

};

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};


// 初始化
onMounted(() => {
  getPage();
  getCategory();
});
</script>
<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
.el-dropdown {
  vertical-align: top;
}
</style>
